package com.hurl.waguji.biz.download;

import java.text.ParseException;
import java.util.Date;

import org.apache.log4j.Logger;
import org.hibernate.ScrollableResults;
import org.hibernate.criterion.Restrictions;

import com.hurl.library.http.HttpException;
import com.hurl.library.http.HttpRequest;
import com.hurl.library.util.DateUtils;
import com.hurl.library.util.StringUtils;
import com.hurl.waguji.base.DateService;
import com.hurl.waguji.base.SqlReader;
import com.hurl.waguji.base.dao.HibernateDao;
import com.hurl.waguji.base.dao.HibernateService;
import com.hurl.waguji.base.dataprocess.ProcessHelper;
import com.hurl.waguji.base.dataprocess.ProcessResult;
import com.hurl.waguji.base.dataprocess.ProcessException;
import com.hurl.waguji.base.dataprocess.ProcessParams;
import com.hurl.waguji.persistence.DmGpBO;
import com.hurl.waguji.persistence.JcsjCjmxTencentBO;

public class MrhqCjmxTencentIdentifier extends DownloadIdentifier {
	private static final Logger log = Logger.getLogger(MrhqCjmxTencentIdentifier.class);
	private Date lastTradingTime = null;
	private Date lastTradingDate = null;
	private String datestr = null;
	private int count = 0;
	
	public MrhqCjmxTencentIdentifier() {
		super("jcsj.mrhq.cjmx.tencent", "【下载】每日成交明细（腾讯网）");
	}

	@Override
	public BaseDownloadProcessor newProcessor(ProcessParams params) {
		throw new UnsupportedOperationException("不需要使用这个方法不支持该操作！");
	}
	
	/**
	 * 验证是否可以下载：
	 * 1）已经下载过不能下载
	 * 2）不再交易日当天不能下载
	 * @throws ProcessException
	 */
	private void validate(HibernateDao dao)throws ProcessException{
		/* 不能重复下载 */
		/*if(ProcessHelper.isAlreadyProcessed(this.getId(), lastTradingDate, dao)){
			throw new ProcessException(DateUtils.formatDate(lastTradingDate, DateUtils.FORMAT_DATE_CN)+"的数据已经下载过！");
		}*/
		
		/* 只能在交易当天下载  */
		
		if(!DateService.isNowAfterTradingTime(lastTradingTime,1)){
			throw new ProcessException("请在交易日下午4点以后下载！");
		}
	}
	
	private void doDownload(DmGpBO bo, Date startTime,HttpRequest requester,HibernateDao dao) throws ParseException, HttpException{
		int p=0;
		String url = null;
		String text = null;
		while(true){
			url = "http://stock.gtimg.cn/data/index.php?appn=detail&action=data&c="+bo.getGpDm().toLowerCase()+"&p="+p;
			String html = requester.request(url);
			if(StringUtils.isBlank(html)){
				break;
			}
			
			text = StringUtils.substringBetween(html, "\"", "\"");
			if(StringUtils.isBlank(text)){
				break;
			}
			
			String[] list = text.split("\\|");
			for(String str : list){
				String[] itemlist = str.split("/");
				JcsjCjmxTencentBO mxbo = new JcsjCjmxTencentBO();
				mxbo.setGpdm(bo.getGpDm());
				mxbo.setRq(lastTradingDate);
				mxbo.setSj(DateUtils.parseDate(itemlist[1], "HH:mm:ss"));
				mxbo.setCjjg(Double.valueOf(itemlist[2]));
				mxbo.setJgbd(Double.valueOf(itemlist[3]));
				mxbo.setCjl(Integer.parseInt(itemlist[4])*100);
				mxbo.setCjje(Double.valueOf(itemlist[5]));
				mxbo.setXz(itemlist[6].charAt(0));
				mxbo.setLastupdate(startTime);
				
				dao.save(mxbo);
				count++;
				if(count%20==0){
					dao.flush();
					dao.clear();
				}
			}
			p++;
		}
	}
	
	public synchronized ProcessResult execute(ProcessParams params)throws ProcessException{
		lastTradingTime = DateService.getLastTradingTimeFromWeb();
		lastTradingDate = DateUtils.getDate(lastTradingTime);
		datestr = DateUtils.formatDate(lastTradingDate, "yyyy-MM-dd");
		count = 0;
		HibernateDao dao = HibernateService.getDao();
		HttpRequest requester = new HttpRequest();
		Date startTime = DateService.getCurrentTimeFromServer();
		DmGpBO bo = null;
		try{
			validate(dao);
			
			ScrollableResults results = dao.createCriteria(DmGpBO.class).add(Restrictions.eq("flag", 'Y')).setReadOnly(true).scroll();
			while(results.next()){
				bo = (DmGpBO)results.get(0);
				
				if(dao.queryBySQL(SqlReader.getSql("SQL12041501", new String[]{bo.getGpDm(),datestr})).setReadOnly(true).list().size()>0){
					log.debug("已经下载过这项，跳过:"+bo.getGpDm()+"-"+datestr);
					continue;
				}
				
				doDownload(bo,startTime,requester,dao);
			}

			dao.flush();
			dao.clear();
			
			/* 保存成功下载结果 */
			ProcessResult result = new ProcessResult(this);
			result.setCount(count);
			result.setRq(lastTradingDate);
			result.setStartTime(startTime);
			result.setEndTime(DateService.getCurrentTimeFromServer());
			result.setSuccess(true);
			ProcessHelper.saveProcessResult(result,dao);
			dao.flush();
			dao.clear();
			log.debug("下载成功！");
			return result;
		}catch(Throwable t){
			log.debug("下载失败！");
			log.error(t.getMessage(),t);
			if(bo!=null){
				//删除刚才下载的数据
				dao.queryBySQL(SqlReader.getSql("SQL12041502", new String[]{bo.getGpDm(),datestr})).executeUpdate();
			}
			/* 保存失败的下载结果 */
			ProcessResult result = new ProcessResult(this);
			result.setCount(count);
			result.setRq(lastTradingDate);
			result.setStartTime(startTime);
			result.setEndTime(DateService.getCurrentTimeFromServer());
			result.setSuccess(false);
			result.setError(t);
			ProcessHelper.saveProcessResult(result,dao);
			dao.flush();
			dao.clear();
			return result;
		}
	}
}
